package raft

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func (r *Raft) InitBuiltinHttpServices() {
	r.RegisterHttpService("/masters/status", r.GetMastersStatus, "GET")
	r.RegisterHttpService("/workers/status", r.GetWorkersStatus, "GET")

}

func (r *Raft) RegisterHttpService(url string, method func(gc *gin.Context), rtype string) {
	switch rtype {
	case "GET":
		r.HttpServer.GET(url, method)
	case "POST":
		r.HttpServer.POST(url, method)
	default:
		r.HttpServer.GET(url, method)

	}
}

func (r *Raft) GetMastersStatus(gc *gin.Context) {
	num := len(r.Peers)
	data := make([]gin.H, num)
	i := 0
	for _, p := range r.Peers {
		msg := gin.H{
			"Addr": p.Addr,
			"Role": p.Role,
		}
		data[i] = msg
		i++
	}
	gc.JSON(http.StatusOK, gin.H{
		"code":   "200",
		"result": data,
	})
}

func (r *Raft) GetWorkersStatus(gc *gin.Context) {
	num := len(r.Workers)
	data := make([]gin.H, num)
	i := 0
	for _, w := range r.Workers {
		msg := gin.H{
			"Addr": w.Addr,
			"Role": "Worker",
			"Img":  "https://assets.appsmith.com/widgets/default.png",
		}
		data[i] = msg
		i++
	}
	gc.JSON(http.StatusOK, gin.H{
		"code": "200",
		"data": data,
	})
}
